package com.speily.current;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @Auther: SPL
 * @Date: 2019-08-05 14:01
 * @Description: - 管道通信
 */
public class PipedTest {

    //输入流和输出流需要首先建立连接。这样线程 B 就可以收到线程 A 发出的消息了。

    public static void main(String[] args) throws IOException {
        //面向于字符 PipedInputStream 面向于字节
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();

        //输入输出流建立连接
        writer.connect(reader);

        Thread t1 = new Thread(() -> {
            System.out.println("running");
            try {
                for (int i = 0; i < 5; i++) {

                    Thread.sleep(2000);
                    writer.write(i + "");
                }
            } catch (Exception e) {
                //...
            } finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
        Thread t2 = new Thread(() -> {
            System.out.println("running2");
            int msg = 0;
            try {
                while ((msg = reader.read()) != -1) {
                    System.out.println("msg=" + (char) msg);
                }

            } catch (Exception e) {
                //...
            }
        });

        t1.start();
        t2.start();
    }
}
